
from models.db import Base, session
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from sqlalchemy.sql import exists


class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(100), unique=True)
    password = Column(String(100), nullable=True)
    create_time = Column(DateTime, default=datetime.now)

    def __repr__(self):
        return self.username

    @classmethod
    def add_user(cls, username, password):
        """
        添加用户
        :param username:
        :param password:
        :return:
        """
        user = User(username=username, password=password)
        session.add(user)
        session.commit()

    @classmethod
    def get_password(cls, username):
        """
        获取密码
        :param username:
        :return:
        """
        user = session.query(User).filter_by(username=username).first()
        if user:
            return user.password
        return None

    @classmethod
    def is_exists(cls, username):
        """
        判断用户是否注册
        :param username:
        :return:
        """
        return session.query(exists().where(User.username==username)).scalar()


class Post(Base):
    __tablename__ = "post"

    id = Column(Integer, primary_key=True, autoincrement=True)
    image_url = Column(String(200))
    thumb_url = Column(String(200))

    user_id = Column(Integer, ForeignKey("users.id"))
    user = relationship("User", backref="post")

    def __repr__(self):
        return self.id

    @classmethod
    def add_post_for(cls, image_url, thumb_url, username):
        user = session.query(User).filter_by(username=username).first()
        post = Post(image_url=image_url, thumb_url=thumb_url, user=user)
        session.add(post)
        session.commit()
